﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaFinwater;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaFinwater;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.Common.Model.NPOI;
using YNTK.Common.Configuration;
using YNTK.DataEncryption;
using YNTK.ClayObject;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaFinwater
{
    /// <summary>
    /// 流水记账服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev", Name = "ZyOaFinwater", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaFinwaterService : IZyOaFinwaterService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaFinwaterEntity> _zyOaFinwaterRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaFinwaterService"/>类型的新实例
        /// </summary>
        public ZyOaFinwaterService(
            ISqlSugarRepository<ZyOaFinwaterEntity> zyOaFinwaterRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyOaFinwaterRepository = zyOaFinwaterRepository;
            _db = _zyOaFinwaterRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取流水记账
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaFinwaterEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaFinwaterInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取流水记账列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaFinwaterListQueryInput input)
        {
            var sidx = input.sidx == null ? "happenDate" : input.sidx;
            List<string> queryHappenDate = input.happenDate != null ? input.happenDate.Split(',').ToObeject<List<string>>() : null;
            DateTime? startHappenDate = queryHappenDate != null ? Ext.GetDateTime(queryHappenDate.First()) : null;
            DateTime? endHappenDate = queryHappenDate != null ? Ext.GetDateTime(queryHappenDate.Last()) : null;
            var data = await _db.Queryable<ZyOaFinwaterEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.proName), p => p.ProName.Equals(input.proName))
                .WhereIF(queryHappenDate != null, p => Convert.ToDateTime(p.HappenDate) >= new DateTime(startHappenDate.ToDate().Year, startHappenDate.ToDate().Month, startHappenDate.ToDate().Day, 0, 0, 0))
                .WhereIF(queryHappenDate != null, p => Convert.ToDateTime(p.HappenDate) <= new DateTime(endHappenDate.ToDate().Year, endHappenDate.ToDate().Month, endHappenDate.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.finType), p => p.FinType.Equals(input.finType))
                .Select(it => new
                {
                    id = it.Id,
                    proName = it.ProName,
                    happenDate = it.HappenDate,
                    finType = it.FinType,
                    bankAmount = it.BankAmount,
                    inAmount = it.InAmount,
                    outAmount = it.OutAmount,
                    desPerson = it.DesPerson,
                    desPersonName = it.DesPersonName,
                    reason = it.Reason,
                    spare1 = it.Spare1,
                    creater = it.Creater,
                    createTime = it.CreateTime,
                }).MergeTable().Select<ZyOaFinwaterListOutput>().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return TkPageResult<ZyOaFinwaterListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建流水记账
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaFinwaterCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaFinwaterEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.Spare1 = await _billRuleService.GetBillNumber("ZYLS");
            entity.Creater = _userManager.UserId;
            entity.CreateTime = DateTime.Now;
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
		/// 获取流水记账无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] ZyOaFinwaterListQueryInput input)
        {
            var sidx = input.sidx == null ? "happenDate" : input.sidx;
            List<string> queryHappenDate = input.happenDate != null ? input.happenDate.Split(',').ToObeject<List<string>>() : null;
            DateTime? startHappenDate = queryHappenDate != null ? Ext.GetDateTime(queryHappenDate.First()) : null;
            DateTime? endHappenDate = queryHappenDate != null ? Ext.GetDateTime(queryHappenDate.Last()) : null;
            var data = await _db.Queryable<ZyOaFinwaterEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.proName), p => p.ProName.Equals(input.proName))
                .WhereIF(queryHappenDate != null, p => Convert.ToDateTime(p.HappenDate) >= new DateTime(startHappenDate.ToDate().Year, startHappenDate.ToDate().Month, startHappenDate.ToDate().Day, 0, 0, 0))
                .WhereIF(queryHappenDate != null, p => Convert.ToDateTime(p.HappenDate) <= new DateTime(endHappenDate.ToDate().Year, endHappenDate.ToDate().Month, endHappenDate.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.finType), p => p.FinType.Equals(input.finType))
                .Select(it => new
                {
                    id = it.Id,
                    proName = it.ProName,
                    happenDate = it.HappenDate,
                    finType = it.FinType,
                    bankAmount = it.BankAmount,
                    inAmount = it.InAmount,
                    outAmount = it.OutAmount,
                    desPerson = it.DesPerson,
                    desPersonName = it.DesPersonName,
                    reason = it.Reason,
                    spare1 = it.Spare1,
                    creater = it.Creater,
                    createTime = it.CreateTime,
                }).MergeTable().Select<ZyOaFinwaterListOutput>().OrderBy(sidx + " " + input.sort).ToListAsync();
            return data;
        }

        /// <summary>
		/// 导出流水记账
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ZyOaFinwaterListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<ZyOaFinwaterListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<TkPageResult<ZyOaFinwaterListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"流水编号\",\"field\":\"spare1\"},{\"value\":\"费用归口\",\"field\":\"proName\"},{\"value\":\"发生时间\",\"field\":\"happenDate\"},{\"value\":\"费用类型\",\"field\":\"finType\"},{\"value\":\"总额(元)\",\"field\":\"bankAmount\"},{\"value\":\"入账金额(元)\",\"field\":\"inAmount\"},{\"value\":\"出账金额(元)\",\"field\":\"outAmount\"},{\"value\":\"经办人\",\"field\":\"desPerson\"},{\"value\":\"协办成员\",\"field\":\"desPersonName\"},{\"value\":\"费用事由\",\"field\":\"reason\"},{\"value\":\"创建人\",\"field\":\"creater\"},{\"value\":\"创建时间\",\"field\":\"createTime\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "流水记账.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<ZyOaFinwaterListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "YNTK")
            };
            return output;
        }

        /// <summary>
        /// 更新流水记账
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaFinwaterUpInput input)
        {
            var entity = input.Adapt<ZyOaFinwaterEntity>();
            entity.Modifyer = _userManager.UserId;
            entity.ModifyTime = DateTime.Now;
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除流水记账
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaFinwaterEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaFinwaterEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
